package com.ficus.road.maintain.controller.smart;

import com.ficus.road.maintain.converter.SmartHitConverter;
import com.ficus.road.maintain.core.model.Hit;
import com.ficus.road.maintain.core.model.RoadTypeEnum;
import com.ficus.road.maintain.core.model.smart.*;
import com.ficus.road.maintain.core.model.smartnew.SmartScreening;
import com.ficus.road.maintain.dao.smart.*;
import com.ficus.road.maintain.service.HitService;
import com.ficus.road.maintain.service.smartnew.SmartScreeningService;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
public class SmartController {
    private final HighwayComplainDao highwayComplainDao;
    private final RoadComplainDao roadComplainDao;
    private final RoadDecisionDao roadDecisionDao;
    private final RoadEngineeringDao roadEngineeringDao;
    private final RoadMaintenanceDao roadMaintenanceDao;
    private final RoadRanktableDao roadRanktableDao;
    private final RoadWarehouseDao roadWarehouseDao;
    private final HitService hitService;
    private final SmartScreeningService smartScreeningService;

    // 道路智能巡查
    @RequestMapping(value = "/smartDiscovery/road/inspection",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<SmartHit>> listRoadInspection(@Min(0) @Valid @RequestParam(defaultValue = "0") Integer start,
                                                             @Min(1) @Valid @RequestParam(defaultValue = "1000") Integer limit) {
        Query query = new Query(Criteria.where("attrs.smart_road_sec_type").is(RoadTypeEnum.ROAD.toString()));
        query.skip(start).limit(limit);
        List<Hit> hitList = hitService.findHitBySmart(query);
        List<SmartHit> smartHitList = hitList.stream().map(item -> SmartHitConverter.convert(item)).collect(Collectors.toList());
        return new ResponseEntity<>(smartHitList, HttpStatus.OK);
    }

    // 道路初筛
    @RequestMapping(value = "/smartDiscovery/road/prescreening",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<RoadDiseaseCount>> listRoadPrescreening() {
        List<RoadDiseaseCount> result = new ArrayList<>();
        Query query = new Query(Criteria.where("road_type").is(RoadTypeEnum.ROAD.toString()));
        List<SmartScreening> smartScreenings = smartScreeningService.statisticAnnually(query);
        Map<String, List<SmartScreening>> groupingMap = smartScreenings.stream().collect(Collectors.groupingBy(SmartScreening::getRoadName));
        groupingMap.forEach((roadName, list) -> {
            RoadDiseaseCount roadDiseaseCount = RoadDiseaseCount.builder().road(roadName).id(list.get(0).getId()).count(list.size()).build();
            result.add(roadDiseaseCount);
        });
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    // todo: 公路智能发现投诉数据
    @RequestMapping(value = "/smartDiscovery/highway/complain",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<Complain>> listHighwayComplain() {
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC, "total"));
        List<Complain> complainList = highwayComplainDao.findByQuery(query);
        return new ResponseEntity<>(complainList, HttpStatus.OK);
    }

    // todo: 道路智能发现投诉数据
    @RequestMapping(value = "/smartDiscovery/road/complain",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<Complain>> listRoadComplain() {
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC, "total"));
        List<Complain> complainList = roadComplainDao.findByQuery(query);
        return new ResponseEntity<>(complainList, HttpStatus.OK);
    }

    // todo: 道路智能发现投诉数据
    @RequestMapping(value = "/smartDiscovery/road/complainPage",
            produces = {"application/json"},
            method = RequestMethod.GET)
//    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity< PageInfo<Complain>> listRoadComplainPage() {

        PageInfo<Complain> listByPage = roadComplainDao.findListByPage(1, 10);
        return new ResponseEntity<>(listByPage, HttpStatus.OK);
    }

    // todo: 道路智能检测工程项目路段
    @RequestMapping(value = "/smartInspect/road/engineering",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<RoadEngineering>> listRoadEngineering() {
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC, "area"));
        List<RoadEngineering> roadEngineeringList = roadEngineeringDao.findByQuery(query);
        return new ResponseEntity<>(roadEngineeringList, HttpStatus.OK);
    }

    // todo: 道路智能检测日常养护
    @RequestMapping(value = "/smartInspect/road/maintenance",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<RoadDiseaseCount>> listRoadMaintenance() {
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC, "count"));
        List<RoadDiseaseCount> roadDiseaseCountList = roadMaintenanceDao.findByQuery(query);
        return new ResponseEntity<>(roadDiseaseCountList, HttpStatus.OK);
    }

    // todo: 道路智能检测储备库路段
    @RequestMapping(value = "/smartInspect/road/warehouse",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<RoadWarehouse>> listRoadWarehouse() {
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC, "area"));
        List<RoadWarehouse> roadWarehouseList = roadWarehouseDao.findByQuery(query);
        return new ResponseEntity<>(roadWarehouseList, HttpStatus.OK);
    }

    // todo: 道路智能排序排分表路段
    @RequestMapping(value = "/smartRank/road/rankTable",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<RoadRanktable>> listRoadRankTable() {
        Query query = new Query();
        Sort.Order bigTypeSort = new Sort.Order(Sort.Direction.ASC, "rank_type");
        Sort.Order areaSort = new Sort.Order(Sort.Direction.DESC, "area");
        query.with(Sort.by(Lists.newArrayList(bigTypeSort, areaSort)));
        List<RoadRanktable> roadRanktableList = roadRanktableDao.findByQuery(query);
        return new ResponseEntity<>(roadRanktableList, HttpStatus.OK);
    }

    // todo: 道路智能决策清单
    @RequestMapping(value = "/smartDecision/road/list",
            produces = {"application/json"},
            method = RequestMethod.GET)
    @PreAuthorize("@rm.check('SMART')")
    public ResponseEntity<List<RoadDecision>> listRoadDecisionList() {
        Query query = new Query();
        Sort.Order bigTypeSort = new Sort.Order(Sort.Direction.ASC, "rank_type");
        Sort.Order investmentSort = new Sort.Order(Sort.Direction.DESC, "investment");
        query.with(Sort.by(Lists.newArrayList(bigTypeSort, investmentSort)));
        List<RoadDecision> roadDecisionList = roadDecisionDao.findByQuery(query);
        return new ResponseEntity<>(roadDecisionList, HttpStatus.OK);
    }

    @PostMapping("/smartDecision/table/import")
    public ResponseEntity<String> importTableData(MultipartFile file) {

        return new ResponseEntity<>("success", HttpStatus.OK);
    }
}
